package com.soft.collateral.service.impl;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.soft.collateral.exception.CollateralException;
import com.soft.collateral.service.FileService;
import com.soft.collateral.utils.QiniuUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;
import java.util.UUID;
/**
 * @author liubin
 * @desc TODO
 * @date 2025/8/1
 */
@Service
public class QiNiuYunFileServiceImpl implements FileService {

    private final QiniuUtils qiniuUtils;
    private Auth auth;
    private UploadManager uploadManager;
    private BucketManager bucketManager;

    public QiNiuYunFileServiceImpl(QiniuUtils qiniuUtils){
        this.qiniuUtils = qiniuUtils;
    }

    @PostConstruct
    public void init() {
        //鉴权
        this.auth = Auth.create(qiniuUtils.getAccessKey(), qiniuUtils.getSecretKey());
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        this.uploadManager = new UploadManager(cfg);
        this.bucketManager =new BucketManager(auth, cfg);
    }

    /**
     * 上传文件
     * @param file
     * @return
     */
    @Override
    public String uploadFile(MultipartFile file) {

        if(file!=null){
            String oldName = file.getOriginalFilename();

            if(StringUtils.hasLength(oldName) && oldName.lastIndexOf(".")>0){
                String fileName  = UUID.randomUUID()+oldName;

                //文件上传
                String token = auth.uploadToken(qiniuUtils.getBucket());
                String key = fileName;
                try {
                    try {
                        //上传
                        Response response = uploadManager.put(file.getInputStream(), key, token, null, null);
                        //解析上传成功的结果
                        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                        //返回存储在七牛云上的外链地址
                        return qiniuUtils.getHostName()+"/"+putRet.key;
                    } catch (QiniuException ex) {
                        ex.printStackTrace();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 上传字节数组文件
     * @param fileBytes
     * @param fileName
     * @return
     */
    @Override
    public String uploadFile(byte[] fileBytes, String fileName) {
        if (fileBytes != null && fileBytes.length > 0 && StringUtils.hasLength(fileName)) {
            try (ByteArrayInputStream inputStream = new ByteArrayInputStream(fileBytes)) {
                // 文件上传
                String token = auth.uploadToken(qiniuUtils.getBucket());
                String key = fileName;

                // 上传
                Response response = uploadManager.put(inputStream, key, token, null, null);
                // 解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                // 返回存储在七牛云上的外链地址
                return qiniuUtils.getHostName() + "/" + putRet.key;
            } catch (QiniuException ex) {
                ex.printStackTrace();
                throw new CollateralException("文件上传失败: " + ex.getMessage());
            } catch (Exception ex) {
                ex.printStackTrace();
                throw new CollateralException("文件上传失败");
            }
        }
        return null;
    }

    /**
     * 删除文件
     * @param url
     * @return
     */
    @Override
    public boolean deleteFile(String url) {

        String fileName = url.replaceAll(qiniuUtils.getHostName()+"/" , "");

        try {
            if(StringUtils.hasLength(fileName)){
                Response response = bucketManager.delete(qiniuUtils.getBucket(), fileName);
                if (response.statusCode == 200) {
                    return true;
                }
            }
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.out.println(fileName + "----删除失败----" + ex.code());
            throw new CollateralException(fileName + "----删除失败----" + ex.code());
        }
        return false;
    }

}
